﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace TiecCuoi
{
    public partial class DatTiec : Form
    {
        bool _LoiInsert = false;
        string _MAHD,_MADATBAN;
        //Data base
        private SqlConnection _CNN;
        // cac bien de ta giao dien
        //Color error
        Color _color1, _color2;
        bool _IsERROR = false;
        int _Index = 0;//tap hien hanh 0->4
        //Listview 
        ListView listSanh = new ListView();
        ListView listMonAn = new ListView();
        ListView listDV = new ListView();
        //thong tin de luu
        string _MaSanh,_MaCa;
        int _Giatoithieu;
        long _GiaMotBan;
        int _Slbantoida;
        int _SlbanDAt;
        int _Slbansutru;
        string _SoDt;
        long _ThanhTien;
        long _TongTienBan;
        long _TienDatcoc;
        long _TongTienDV;
        long _TienConLai;
        int _indexDV = -1;
        public DatTiec(SqlConnection cnn)
        {
            _CNN = cnn;
            InitializeComponent();
            TaoListSanh();
            TaoListMonAn();
            TaoListDichVu();
            TaoCompo();
            LoadDataViewMA();
            LoadDataViewDV();
            _color1 = Color.White;
            _color2 = Color.Red;

        }

        private void TaoListSanh()
        {
            // Create a new ListView control.
            //ListView listView1 = new ListView();
            listSanh.Bounds = new Rectangle(new Point(9, 148), new Size(483, 269));

            // Set the view to show details.
            listSanh.View = View.Details;
            // Allow the user to edit item text.
            listSanh.LabelEdit = true;
            // Allow the user to rearrange columns.
            listSanh.AllowColumnReorder = true;
            // Display check boxes.
            listSanh.CheckBoxes = true;
            // Select the item and subitems when selection is made.
            listSanh.FullRowSelect = true;
            // Display grid lines.
            listSanh.GridLines = true;
            //Su kien check
            listSanh.ItemCheck += new ItemCheckEventHandler(listSanh_ItemCheck);

            // Create columns for the items and subitems.
            // Width of -2 indicates auto-size.
            listSanh.Columns.Add("Chọn", -2, HorizontalAlignment.Left);
            listSanh.Columns.Add("Mã sảnh", -2, HorizontalAlignment.Left);
            listSanh.Columns.Add("Tên sảnh", -2, HorizontalAlignment.Left);
            listSanh.Columns.Add("Loại mã sảnh", -2, HorizontalAlignment.Left);
            listSanh.Columns.Add("Số lượng bàn tối đa", -2, HorizontalAlignment.Center);
            // Add the ListView to the control collection.
            this.tabPage1.Controls.Add(listSanh);
            //Add the items to the ListView.
        }

        void listSanh_ItemCheck(object sender, ItemCheckEventArgs e)
        {

            //CheckSanh();
            //MessageBox.Show("Chọn sảnh trước!", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.None);

        }

        //Tao danh sach mon an
        private void TaoListMonAn()
        {
            // Create a new ListView control.
            //ListView listView1 = new ListView();
            listMonAn.Bounds = new Rectangle(new Point(6, 71), new Size(502, 330));

            // Set the view to show details.
            listMonAn.View = View.Details;
            // Allow the user to edit item text.
            listMonAn.LabelEdit = true;
            // Allow the user to rearrange columns.
            listMonAn.AllowColumnReorder = true;
            // Display check boxes.
            listMonAn.CheckBoxes = true;
            // Select the item and subitems when selection is made.
            listMonAn.FullRowSelect = true;
            // Display grid lines.
            listMonAn.GridLines = true;
            //Lay thong tin mon an



            // Create columns for the items and subitems.
            // Width of -2 indicates auto-size.
            listMonAn.Columns.Add("Chọn", -2, HorizontalAlignment.Left);
            listMonAn.Columns.Add("Mã món ăn", -2, HorizontalAlignment.Left);
            listMonAn.Columns.Add("Tên món ăn", -2, HorizontalAlignment.Left);
            listMonAn.Columns.Add("Đơn giá", -2, HorizontalAlignment.Left);
            // Add the ListView to the control collection.
            this.tabPage2.Controls.Add(listMonAn);
            //Add the items to the ListView.


        }

        //Tao list dich vu
        private void TaoListDichVu()
        {
            // Create a new ListView control.
            //ListView listView1 = new ListView();
            listDV.Bounds = new Rectangle(new Point(6, 71), new Size(502, 330));

            // Set the view to show details.
            listDV.View = View.Details;
            // Allow the user to edit item text.
            listDV.LabelEdit = true;
            // Allow the user to rearrange columns.
            listDV.AllowColumnReorder = true;
            // Display check boxes.
            listDV.CheckBoxes = true;
            // Select the item and subitems when selection is made.
            listDV.FullRowSelect = true;
            // Display grid lines.
            listDV.GridLines = true;
            //Lay thong tin mon an
            listDV.SelectedIndexChanged += new EventHandler(listDV_SelectedIndexChanged);


            // Create columns for the items and subitems.
            // Width of -2 indicates auto-size.
            listDV.Columns.Add("Chọn", -2, HorizontalAlignment.Left);
            listDV.Columns.Add("Mã dịch vu", -2, HorizontalAlignment.Left);
            listDV.Columns.Add("Tên dịch vu", -2, HorizontalAlignment.Left);
            listDV.Columns.Add("Đơn giá", -2, HorizontalAlignment.Left);
            listDV.Columns.Add("Số lượng", -2, HorizontalAlignment.Left);
            // Add the ListView to the control collection.
            this.tabPage3.Controls.Add(listDV);
            //Add the items to the ListView.

        }

        void listDV_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listDV.FocusedItem != null)
            {
                _indexDV = listDV.FocusedItem.Index;
            }
        }

        private void LoadDataviewSanh()
        {
            //xoa list truoc
            listSanh.Items.Clear();
            ListViewItem item;
            bool bool_mau = false;
            int i = 0;
            try
            {
                string ca;
                if (radioButton1.Checked == true)
                {
                    ca = "CA001";
                }
                else
                {
                    ca = "CA002";
                }
                string loaisanh = Compo_LS.SelectedItem.ToString();
                string ngay = dateTimePicker1_ngaysinh.Value.ToShortDateString();
                string sql = "select MaSanh,TenSanh,MaLoaiSanh,SoLuongBanToiDa from SANH where " +
                    "SANH.MaLoaiSanh=@loaisanh and MaSanh NOT IN" +
                    "(select MaSanh from CHITIETDATTIEC,TIECCUOI where CHITIETDATTIEC.MaCa=@Ca and CHITIETDATTIEC.MaTiec=TIECCUOI.MaTiec and TIECCUOI.NgayDaiTiec = @ngay)";
                i++;
                SqlCommand command = new SqlCommand(sql, _CNN);
                command.CommandType = CommandType.Text;
                command.Parameters.AddWithValue("@loaisanh", loaisanh);
                command.Parameters.AddWithValue("@Ca", ca);
                command.Parameters.AddWithValue("@ngay", ngay);




                SqlDataReader read = command.ExecuteReader();
                while (read.Read())
                {
                    item = new ListViewItem("");
                    item.SubItems.Add(read[0].ToString());
                    item.SubItems.Add(read[1].ToString());
                    item.SubItems.Add(read[2].ToString());
                    item.SubItems.Add(read[3].ToString());
                    if (bool_mau == false)
                        item.BackColor = Color.White;
                    else
                        item.BackColor = Color.FromArgb(245, 204, 102);
                    bool_mau = !bool_mau;
                    listSanh.Items.Add(item);
                    i++;
                }
                read.Close();
                command.Dispose();
                read.Dispose();
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
        }

        private void LoadDataViewMA()//khi load form/delete/edit/add
        {
            //xoa list truoc
            listMonAn.Items.Clear();
            ListViewItem item;
            bool bool_mau = false;
            int i = 0;
            try
            {
                string ham = "select MaMonAn,TenMonAn,DonGia from MONAN";
                i++;
                SqlCommand select = new SqlCommand(ham, _CNN);
                SqlDataReader read = select.ExecuteReader();
                while (read.Read())
                {
                    item = new ListViewItem("");
                    item.SubItems.Add(read[0].ToString());
                    item.SubItems.Add(read[1].ToString());
                    item.SubItems.Add(read[2].ToString());
                    if (bool_mau == false)
                        item.BackColor = Color.White;
                    else
                        item.BackColor = Color.FromArgb(245, 204, 102);
                    bool_mau = !bool_mau;
                    listMonAn.Items.Add(item);
                    i++;
                }
                read.Close();
                select.Dispose();
                read.Dispose();
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.tabControl1.SelectTab(_Index);
        }
        //Tao compobox loai sanh
        void TaoCompo()
        {
            try
            {
                string ham = "select MaLoaiSanh from LOAISANH";
                // lấy danh sách lớp từ DaTaBase
                SqlCommand select_lop = new SqlCommand(ham, _CNN);
                SqlDataReader read = select_lop.ExecuteReader();
                while (read.Read())
                {
                    string loaisanh = read[0].ToString();
                    Compo_LS.Items.Add(loaisanh);
                }
                select_lop.Dispose();
                read.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            //comboBox_Lop.SelectedItem = comboBox_Lop.Items[0];
        }
        //load danh sach dich vu
        private void LoadDataViewDV()//khi load form/delete/edit/add
        {
            //reset list truoc
            listDV.Items.Clear();
            ListViewItem item;
            bool bool_mau = false;
            int i = 0;
            try
            {
                string ham = "select MaDichVu,TenDichVu,DonGia from DICHVU";
                i++;
                SqlCommand select = new SqlCommand(ham, _CNN);
                SqlDataReader read = select.ExecuteReader();
                while (read.Read())
                {
                    item = new ListViewItem("");
                    item.SubItems.Add(read[0].ToString());
                    item.SubItems.Add(read[1].ToString());
                    item.SubItems.Add(read[2].ToString());
                    item.SubItems.Add("1");
                    if (bool_mau == false)
                        item.BackColor = Color.White;
                    else
                        item.BackColor = Color.FromArgb(245, 204, 102);
                    bool_mau = !bool_mau;
                    listDV.Items.Add(item);
                    i++;


                }
                read.Close();
                select.Dispose();
                read.Dispose();
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
        }
        //----------------------------------Uncheck
        private void CheckSanh()
        {
            int n = listSanh.Items.Count;
            int i = 0;
            for (i = 0; i < n; i++)
            {
                listSanh.Items[i].Checked = false;
            }

        }

        //------------------------------------Kiem tra gia tri nhap
        private bool KiemTraSanh()
        {
            int soitemcheck = 0;
            //lay check
            foreach (ListViewItem item in listSanh.Items)
            {
                if (item.Checked == true)//lay sanh dc chon
                {
                    ++soitemcheck;
                }
            }
            if(soitemcheck == 1)
            {
                return true;
            }
            if(soitemcheck > 1)
            {
                MessageBox.Show("Chỉ có thể chọn một sảnh!", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return false;

        }
        //-------------------------------kiem tra chon mon an
        private bool KiemTraChonMonAn()
        {
            //lay check
            foreach (ListViewItem item in listMonAn.Items)
            {
                if (item.Checked == true)//lay sanh dc chon
                {
                    _MaSanh = item.SubItems[1].Text;
                    //*     _Giatoithieu = Convert.ToInt32(item.SubItems[1].Text);*/
                    return true;
                }
            }
            return false;
        }
        //------------------------------------------------------------------kiem tra dich vu
        private bool KiemTraDichVu()
        {
            //lay check
            foreach (ListViewItem item in listDV.Items)
            {
                if (item.Checked == true)//lay sanh dc chon
                {
                    _MaSanh = item.SubItems[1].Text;
                    //*     _Giatoithieu = Convert.ToInt32(item.SubItems[1].Text);*/
                    return true;
                }
            }
            return false;
        }
        //-----------------------------------------------------------------------------------kiem tra nhap thong tin
        private bool KiemTraThongtin()
        {
            if(!CheckNULLValues())
            {
                //kiem ta so ban toi da
                string sobandat = textBox_Slbandat.Text.Trim();
                sobandat = sobandat.Replace(",", "");
                this._SlbanDAt = Convert.ToInt32(sobandat);
                if(_SlbanDAt > _Slbantoida)
                {
                    MessageBox.Show("Số lượng bàn đặt phải nhỏ hơn số lượng bàn tối đa", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
                string sobandutru = textBox_slbandutru.Text.Trim();
                sobandutru = sobandutru.Replace(",","");
                this._Slbansutru = Convert.ToInt32(sobandutru);
                if(_Slbansutru >= _SlbanDAt)
                {
                    MessageBox.Show("Số lượng bàn dự trữ phải nhỏ hơn số lượng bàn đạt", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
                _SoDt = textBox_dienthoai.Text.Trim();
                _SoDt = _SoDt.Replace(",", "");
                return true;
                
            }
            return false;
        }
        //Check null values
        private bool CheckNULLValues()
        {
            if (this.textBox_tenRe.Text.Length == 0)
            {
                textBox_tenRe.BackColor = _color2;
                _IsERROR = true;
            }
            if (this.textBox_tenRe.Text.Length < 5)
            {
                textBox_tenRe.BackColor = _color2;
                _IsERROR = true;
            }
            if (this.textBox_tenDau.Text.Length == 0)
            {
                textBox_tenDau.BackColor = _color2;
                _IsERROR = true;
            }
            if (this.textBox_tenDau.Text.Length < 5)
            {
                textBox_tenDau.BackColor = _color2;
                _IsERROR = true;
            }
            if(this.textBox_dienthoai.Text.Length == 0)
            {
                this.textBox_dienthoai.BackColor = _color2;
                _IsERROR = true;
            }
            if (this.textBox_Slbandat.Text.Length == 0)
            {
                this.textBox_Slbandat.BackColor = _color2;
                _IsERROR = true;
            }
            if (this.textBox_slbandutru.Text.Length == 0)
            {
                this.textBox_slbandutru.BackColor = _color2;
                _IsERROR = true;
            }
            if (_IsERROR)//hien thong bao loi
            {
                MessageBox.Show("Thông tin nhập không hợp lệ\nTên phải nhiều hơn 5 ký tự.", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                textBox_tenDau.BackColor = _color1;
                textBox_tenRe.BackColor = _color1;
                textBox_dienthoai.BackColor = _color1;
                textBox_Slbandat.BackColor = _color1;
                textBox_slbandutru.BackColor = _color1;
                //L_Error.Visible = false;
                _IsERROR = false;
                return true;
            }
            return false;

        }
        //-------------------------tinh tien mon an 1 ban
        private void TinhTienMotBan()
        {
            _GiaMotBan = 0;
            foreach (ListViewItem item in listMonAn.Items)
            {
                if (item.Checked == true)//lay sanh dc chon
                {
                    _GiaMotBan += Convert.ToInt32(item.SubItems[3].Text);

                }
            }

        }
        private void TinhTienDV()
        {
            _TongTienDV = 0;
            foreach (ListViewItem item in listDV.Items)
            {
                if (item.Checked == true)//lay sanh dc chon
                {
                    _TongTienDV += Convert.ToInt32(item.SubItems[3].Text) * Convert.ToInt32(item.SubItems[4].Text);

                }
            }
        }

        //lay gia toi thieu
        private void GetGiatoithieu()
        {
            try
            {
                string ham = "select DonGiaBanToiThieu from LOAISANH where MaLoaiSanh='" +
                             Compo_LS.SelectedItem.ToString() + "'";
                SqlCommand select = new SqlCommand(ham, _CNN);
                SqlDataReader read = select.ExecuteReader();
                while (read.Read())
                {
                    _Giatoithieu = Convert.ToInt32(read[0].ToString());

                }
                read.Close();
                select.Dispose();
                read.Dispose();
            }
            catch (Exception emon)
            {
                MessageBox.Show(emon.Message);
            }

        }
        //------------------------------------lay so luong ban toi da
        private void GetSLBanToiDa()
        {

            _Slbantoida = 0;
            foreach (ListViewItem item in listSanh.Items)
            {
                if (item.Checked == true)//lay sanh dc chon
                {
                    _Slbantoida = Convert.ToInt32(item.SubItems[4].Text);

                }
            }
        }

        //----------------------------dieu kien chuyen buoc-----------------------
        //--------- 1---> 2
        private void button2_Click(object sender, EventArgs e)
        {
            if (KiemTraSanh())
            {
                _Index = 1;
                this.tabControl1.SelectTab(_Index);
                GetGiatoithieu();
                L_giatoithieu.Text = _Giatoithieu.ToString();
            }
            else
            {
                MessageBox.Show("Chọn sảnh trước!", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.None);
            }

        }
        //-----------------------------2 -->3
        private void B_back2_Click(object sender, EventArgs e)
        {
            _Index = 0;
            this.tabControl1.SelectTab(_Index);
        }

        private void B_next2_Click(object sender, EventArgs e)
        {
            if (KiemTraChonMonAn())
            {
                TinhTienMotBan();
                if (_GiaMotBan >= _Giatoithieu)//Gia ban >= gia toi thieu
                {
                    _Index = 2;
                    this.tabControl1.SelectTab(_Index);
                }
                else
                {
                    MessageBox.Show("Đơn giá bàn phải >= giá tối thiểu\nĐơn giá hiện tại là: " + _GiaMotBan.ToString(), "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.None);
                }

            }
            else
            {
                MessageBox.Show("Vui lòng chọn món ăn!", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.None);
            }

        }

        private void B_cancel2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        //-----------------------------3 -->4
        private void B_back3_Click(object sender, EventArgs e)
        {
            _Index = 1;
            this.tabControl1.SelectTab(_Index);
        }

        private void B_next3_Click(object sender, EventArgs e)
        {
            _Index = 3;
            this.tabControl1.SelectTab(_Index);
            GetSLBanToiDa();
            L_slbantoida.Text = "Số lượng bàn tối đa: " + _Slbantoida.ToString();

        }

        private void B_cancel3_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        //---------------------------4 -->5
        private void B_back4_Click(object sender, EventArgs e)
        {
            _Index = 2;
            this.tabControl1.SelectTab(_Index);
        }

        private void B_next4_Click(object sender, EventArgs e)
        {

            if(KiemTraThongtin())
            {
                _Index = 4;
                this.tabControl1.SelectTab(_Index);
                _TongTienBan = _GiaMotBan * _SlbanDAt;
                _TongTienDV =  0;
                TinhTienDV();
                _ThanhTien = _TongTienDV + _TongTienBan;
                _TienConLai = _ThanhTien / 2;
                _TienDatcoc = _TienConLai;
                //hien thi
                TB_Tongtienban.Text = _TongTienBan.ToString();
                this.TB_TongtienDV.Text = _TongTienDV.ToString();
                this.TB_Tiendatcoc.Text = _TienDatcoc.ToString();
                this.TB_TienConLai.Text = _TienDatcoc.ToString();
                this.TB_ThanhTien.Text = _ThanhTien.ToString();
            }
            else
            {
                MessageBox.Show("Vui lòng nhập đầy đủ thông tin", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.None);
            }
        }

        private void B_cancel4_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void B_cancel1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Compo_LS_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDataviewSanh();
        }

        //chi cho nhan so
        private void textBox_dienthoai_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void textBox_dienthoai_TextChanged(object sender, EventArgs e)
        {
            TachSo(textBox_dienthoai);
        }
        //-----------------ham tu dong tach so
        public void TachSo(TextBox luong)
        {
            string txt, txt1;
            txt1 = luong.Text.Replace(",", "");
            txt = "";
            int n = txt1.Length;
            int dem = 0;
            for (int i = n - 1; i >= 0; i--)
            {
                if (dem == 2 && i != 0)
                {
                    txt = "," + txt1.Substring(i, 1) + txt;
                    dem = 0;
                }
                else
                {
                    txt = txt1.Substring(i, 1) + txt;
                    dem += 1;
                }
            }
            luong.Text = txt;
            luong.SelectionStart = luong.Text.Length;
        }

        private void textBox_Slbandat_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;

            }
        }

        private void textBox_Slbandat_TextChanged(object sender, EventArgs e)
        {
            TachSo(textBox_Slbandat);
        }

        private void textBox_slbandutru_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;

            }
        }

        private void textBox_slbandutru_TextChanged(object sender, EventArgs e)
        {
            TachSo(textBox_slbandutru);
        }

        private void B_back5_Click(object sender, EventArgs e)
        {
            _Index = 3;
            this.tabControl1.SelectTab(_Index);
        }
        //--------------------------------------------------------------------Dat tiec
        private void B_Dattiec_Click(object sender, EventArgs e)
        {
            //InsertTiecCuoi();
            //if (_LoiInsert == true)
            //{
            //    MessageBox.Show("Insert Thất bại!", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    _LoiInsert = false;
            //}
            //else
            //{
            //    MessageBox.Show("Insert Thành công!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.None);
            //    this.Close();
            //}

            LayMaSanhMaCa();
            string MaTiec = TaoMaTiecCuoi();
            string MaChiTietDatTiec = CreateMaChiTietDatTiec(MaTiec);
            string MaHoaDon = CreateMaHD();
            string MaDatBan = TaoMaDatBan();
            string MaChiTietMonAn = TaoMaChiTietMonAn();
            string MaChiTietDichVu = TaoMaChiTietDichVu();
            string MaChiTietHoaDon = CreateMaCTHD(MaHoaDon);
            //--1 ---insert Tiec Cuoi
            InsertTiecCuoi(MaTiec);
            //--2 ---insert CHITIETDATTIEC
            InsertChiTietTiecCuoi(MaChiTietDatTiec,MaTiec);
            //---3--insert hoa don
            InsertHoaDon(MaHoaDon,MaTiec);
            //--4 --insert DATBAN
            InsertMaDatBan(MaDatBan,MaTiec);
            //--5 --insert CHITIETMONAN
            foreach (ListViewItem item in listMonAn.Items)
            {
                string mamonan;
                if (item.Checked == true)//lay sanh dc chon
                {
                    mamonan = item.SubItems[1].Text;
                    InsertChiTietMonAn(mamonan, MaDatBan);
                    if (_LoiInsert == true)
                    {
                        return;
                    }
                }
            }
            //--6--insert CHITIETDICHVU
            //InsertChiTietDichVu(,_MADATBAN,,);
            foreach (ListViewItem item in listDV.Items)
            {
                string madv;
                int intsoluong, intdongia, inttien;
                string soluong, thanhtien;
                if (item.Checked == true)//lay sanh dc chon
                {
                    madv = item.SubItems[1].Text;
                    soluong = item.SubItems[4].Text;
                    intsoluong = Convert.ToInt32(soluong);
                    intdongia = Convert.ToInt32(item.SubItems[3].Text);
                    inttien = intdongia * intsoluong;
                    thanhtien = inttien.ToString();
                    InsertChiTietDichVu(madv,MaDatBan, soluong, thanhtien);
                    if (_LoiInsert == true)
                    {
                        return;
                    }
                }
            }
            if (_LoiInsert == true)
            {
                MessageBox.Show("Insert Thất bại!", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _LoiInsert = false;
            }
            else
            {
                MessageBox.Show("Insert Thành công!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.None);
                this.Close();
            }
        }

        private void B_Cancel5_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void B_GiamSL_Click(object sender, EventArgs e)
        {
            if (_indexDV == -1)
            {
                MessageBox.Show("Chọn dịch vụ cần giảm trước!", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (listDV.Items[_indexDV].Checked == false)
            {
                return;
            }
            int so = Convert.ToInt32(listDV.Items[_indexDV].SubItems[4].Text.Trim());
            --so;
            if(so<1)
            {
                so = 1;
            }
            listDV.Items[_indexDV].SubItems[4].Text = so.ToString();
        }

        private void B_TangSL_Click(object sender, EventArgs e)
        {
            if (_indexDV == -1)
            {
                MessageBox.Show("Chọn dịch vụ cần tăng trước!", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (listDV.Items[_indexDV].Checked == false)
            {
                return;
            }
            int so = Convert.ToInt32(listDV.Items[listDV.FocusedItem.Index].SubItems[4].Text.Trim());
            ++so;
            listDV.Items[_indexDV].SubItems[4].Text = so.ToString();
        }

        //-----------------------------------------Tu tao ma
        private string TaoMaDatBan()
        {
            string maso = string.Empty;
            try
            {
                string cmd = "select top(1) *  from DATBAN ORDER BY MaDatBan desc";
                SqlCommand command = new SqlCommand(cmd, _CNN);
                SqlDataReader read = command.ExecuteReader();
                if (read.Read())
                {
                    maso = read[0].ToString();
                }
                if (maso == "")
                {
                    read.Close(); read.Dispose();
                    return "00001";
                }
                if(maso == "loi")
                {
                    maso = "00000";
                }
                read.Close(); read.Dispose();
                int so = Convert.ToInt32(maso);
                for (int i = so + 1; i <= 99999; i++)
                {
                    maso = i.ToString();
                    if (maso.Length == 1)
                        maso = "0000" + maso;
                    if (maso.Length == 2)
                        maso = "000" + maso;
                    if (maso.Length == 3)
                        maso = "00" + maso;
                    if(maso.Length == 4)
                        maso = "0" + maso;

                    string cmd2 = "select MaDatBan from DATBAN Where MaDatBan=@mama ";
                    SqlCommand command2 = new SqlCommand(cmd2, _CNN);
                    command2.Parameters.AddWithValue("@mama", maso);
                    SqlDataReader read2 = command2.ExecuteReader();
                    if (read2.Read())
                    {
                        read2.Close();
                        read2.Dispose();
                        continue;
                    }
                    read2.Close();
                    read2.Dispose();
                    return maso;

                }

            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            return "loi";
        }
        private string TaoMaTiecCuoi()
        {
            string maso = string.Empty;
            try
            {
                string cmd = "select top(1) *  from TIECCUOI ORDER BY MaTiec desc";
                SqlCommand command = new SqlCommand(cmd, _CNN);
                SqlDataReader read = command.ExecuteReader();
                if (read.Read())
                {
                    maso = read[0].ToString();
                }
                if (maso == "")
                {
                    read.Close(); read.Dispose();
                    return "TC001";
                }
                read.Close(); read.Dispose();
                maso = maso.Substring(2, 3);
                int so = Convert.ToInt32(maso);
                for (int i = so + 1; i <= 999; i++)
                {
                    maso = i.ToString();
                    if (maso.Length == 1)
                        maso = "TC00" + maso;
                    if (maso.Length == 2)
                        maso = "TC0" + maso;
                    if (maso.Length == 3)
                        maso = "TC" + maso;

                    string cmd2 = "select MaTiec from TIECCUOI Where MaTiec=@mama ";
                    SqlCommand command2 = new SqlCommand(cmd2, _CNN);
                    command2.Parameters.AddWithValue("@mama", maso);
                    SqlDataReader read2 = command2.ExecuteReader();
                    if (read2.Read())
                    {
                        read2.Close();
                        read2.Dispose();
                        continue;
                    }
                    read2.Close();
                    read2.Dispose();
                    return maso;

                }

            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            return "loi";

              
        }
        private string TaoMaChiTietMonAn()
        {
            string maso = string.Empty;
            try
            {
                string cmd = "select top(1) *  from CHITIETMONAN ORDER BY MaCTMA desc";
                SqlCommand command = new SqlCommand(cmd, _CNN);
                SqlDataReader read = command.ExecuteReader();
                if (read.Read())
                {
                    maso = read[0].ToString();
                }
                if (maso == "")
                {
                    read.Close(); read.Dispose();
                    return "A0001";
                }
                read.Close(); read.Dispose();
                maso = maso.Substring(2, 3);
                int so = Convert.ToInt32(maso);
                for (int i = so + 1; i <= 999; i++)
                {
                    maso = i.ToString();
                    if (maso.Length == 1)
                        maso = "A000" + maso;
                    if (maso.Length == 2)
                        maso = "A00" + maso;
                    if (maso.Length == 3)
                        maso = "A0" + maso;
                    if (maso.Length == 4)
                        maso = "A" + maso;


                    string cmd2 = "select MaCTMA from CHITIETMONAN Where MaCTMA=@mama ";
                    SqlCommand command2 = new SqlCommand(cmd2, _CNN);
                    command2.Parameters.AddWithValue("@mama", maso);
                    SqlDataReader read2 = command2.ExecuteReader();
                    if (read2.Read())
                    {
                        read2.Close();
                        read2.Dispose();
                        continue;
                    }
                    read2.Close();
                    read2.Dispose();
                    return maso;

                }

            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            return "loi";
        }
        //------------
        private string TaoMaChiTietDichVu()
        {
            string maso = string.Empty;
            try
            {
                string cmd = "select top(1) *  from CHITIETDICHVU ORDER BY MaCTDV desc";
                SqlCommand command = new SqlCommand(cmd, _CNN);
                SqlDataReader read = command.ExecuteReader();
                if (read.Read())
                {
                    maso = read[0].ToString();
                }
                if (maso == "")
                {
                    read.Close(); read.Dispose();
                    return "D0001";
                }
                read.Close(); read.Dispose();
                maso = maso.Substring(2, 3);
                int so = Convert.ToInt32(maso);
                for (int i = so + 1; i <= 999; i++)
                {
                    maso = i.ToString();
                    if (maso.Length == 1)
                        maso = "D000" + maso;
                    if (maso.Length == 2)
                        maso = "D00" + maso;
                    if (maso.Length == 3)
                        maso = "D0" + maso;
                    if (maso.Length == 4)
                        maso = "D" + maso;


                    string cmd2 = "select MaCTDV from CHITIETDICHVU Where MaCTDV=@mama ";
                    SqlCommand command2 = new SqlCommand(cmd2, _CNN);
                    command2.Parameters.AddWithValue("@mama", maso);
                    SqlDataReader read2 = command2.ExecuteReader();
                    if (read2.Read())
                    {
                        read2.Close();
                        read2.Dispose();
                        continue;
                    }
                    read2.Close();
                    read2.Dispose();
                    return maso;

                }

            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            return "loi";
        }

        //---------------------------------------------------Insert
        private void InsertMaDatBan(string MaDatBan,string MaTiec)
        {

            try
            {
                string cmd = "INSERT INTO DATBAN VALUES(@MADATBAN,@MATIECCUOI,@SLBAN,@SLBANDUTRU,@DONGIABAN)";
                SqlCommand command = new SqlCommand(cmd, _CNN);
                command.CommandType = CommandType.Text;
                command.Parameters.AddWithValue("@MADATBAN", MaDatBan);
                command.Parameters.AddWithValue("@MATIECCUOI", MaTiec);
                command.Parameters.AddWithValue("@SLBAN", _SlbanDAt.ToString());
                command.Parameters.AddWithValue("@SLBANDUTRU", this._Slbansutru.ToString());
                command.Parameters.AddWithValue("@DONGIABAN", this._GiaMotBan.ToString());
                command.ExecuteNonQuery();
                command.Dispose();
            }
            catch (Exception emon)
            {
                MessageBox.Show(emon.Message);
                _LoiInsert = true;
                return;
            }            
        }

        private void InsertChiTietMonAn(string mamonan,string madatban)
        {
            string ma = TaoMaChiTietMonAn();
            try
            {
                string cmd = "INSERT INTO CHITIETMONAN VALUES(@MACTMA,@MAMA,@MADATBAN)";
                SqlCommand command = new SqlCommand(cmd, _CNN);
                command.CommandType = CommandType.Text;
                command.Parameters.AddWithValue("@MACTMA", ma);
                command.Parameters.AddWithValue("@MAMA", mamonan);
                command.Parameters.AddWithValue("@MADATBAN", madatban);
                command.ExecuteNonQuery();
                command.Dispose();
            }
            catch (Exception emon)
            {
                MessageBox.Show(emon.Message);
                _LoiInsert = true;
                return;
            }
        }

        private void InsertChiTietDichVu(string madv, string madatban,string soluong,string thanhtien)
        {
            string ma = TaoMaChiTietDichVu();
            try
            {
                string cmd = "INSERT INTO CHITIETDICHVU VALUES(@MACTDV,@MADATBAN,@MADV,@SOLUONG,@THANHTIEN)";
                SqlCommand command = new SqlCommand(cmd, _CNN);
                command.CommandType = CommandType.Text;
                command.Parameters.AddWithValue("@MACTDV", ma);
                command.Parameters.AddWithValue("@MADATBAN", madatban);
                command.Parameters.AddWithValue("@MADV", madv);
                command.Parameters.AddWithValue("@SOLUONG", soluong);
                command.Parameters.AddWithValue("@THANHTIEN",thanhtien);
                command.ExecuteNonQuery();
                command.Dispose();
            }
            catch (Exception emon)
            {
                MessageBox.Show(emon.Message);
                _LoiInsert = true;
                return;
            }


        }

        private void InsertTiecCuoi(string ma)
        {
            //insert tiec cuoi
            string ngay = DateTime.Now.Month.ToString() + "/" + DateTime.Now.Day.ToString() + "/" + DateTime.Now.Year.ToString();
            try
            {
                string cmd = "INSERT INTO TIECCUOI VALUES(@MA,@TENRE,@TENDAU,@DIENTHOAI,@NGAY,@NGAYDAI,@TIENCOC)";
                SqlCommand command = new SqlCommand(cmd, _CNN);
                command.CommandType = CommandType.Text;
                command.Parameters.AddWithValue("@MA", ma);
                command.Parameters.AddWithValue("@TENRE",textBox_tenRe.Text.Trim());
                command.Parameters.AddWithValue("@TENDAU",textBox_tenDau.Text.Trim());
                command.Parameters.AddWithValue("@DIENTHOAI",textBox_dienthoai.Text.Trim());
                command.Parameters.AddWithValue("@NGAY", ngay);
                command.Parameters.AddWithValue("@NGAYDAI", dateTimePicker1_ngaysinh.Value.ToShortDateString());
                command.Parameters.AddWithValue("@TIENCOC", _TienDatcoc);
                command.ExecuteNonQuery();
                command.Dispose();
            }
            catch (Exception emon)
            {
                MessageBox.Show(emon.Message);
                _LoiInsert = true;
                return;
            }
        }

        //tao ma hoa don
        private string CreateMaHD()
        {
            string maso = string.Empty;
            try
            {
                string cmd = "select top(1) *  from HOADON ORDER BY MaHoaDon desc";
                SqlCommand command = new SqlCommand(cmd, _CNN);
                SqlDataReader read = command.ExecuteReader();
                if (read.Read())
                {
                    maso = read[0].ToString();
                }
                if (maso == "")
                {
                    read.Close(); read.Dispose();
                    return "HD001";
                }
                read.Close(); read.Dispose();
                maso = maso.Substring(2, 3);
                int so = Convert.ToInt32(maso);
                for (int i = so + 1; i <= 999; i++)
                {
                    maso = i.ToString();
                    if (maso.Length == 1)
                        maso = "HD00" + maso;
                    if (maso.Length == 2)
                        maso = "HD0" + maso;
                    if (maso.Length == 3)
                        maso = "HD00" + maso;

                    string cmd2 = "select MaHoaDon from HOADON Where MaHoaDon=@mama ";
                    SqlCommand command2 = new SqlCommand(cmd2, _CNN);
                    command2.Parameters.AddWithValue("@mama", maso);
                    SqlDataReader read2 = command2.ExecuteReader();
                    if (read2.Read())
                    {
                        read2.Close();
                        read2.Dispose();
                        continue;
                    }
                    read2.Close();
                    read2.Dispose();
                    return maso;

                }

            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            return "loi";
        }

       private string CreateMaCTHD(string maHD)
       {
           string ma = "CT" + maHD;
           return ma;
       }
        private string CreateMaChiTietDatTiec(string matieccuoi)
        {
            string ma = "CT" + matieccuoi;
            return ma;
        }

        //----------------------------------insert CTTC
        private void InsertChiTietTiecCuoi(string MACTTC,string matieccuoi)
        {
            //insert tiec cuoi
           // string ma = CreateMaChiTietDatTiec(matieccuoi);
            LayMaSanhMaCa();
            try
            {
                string cmd = "INSERT INTO CHITIETDATTIEC VALUES(@MACT,@MATIEC,@MACA,@MASANH)";
                SqlCommand command = new SqlCommand(cmd, _CNN);
                command.CommandType = CommandType.Text;
                command.Parameters.AddWithValue("@MACT", MACTTC);
                command.Parameters.AddWithValue("@MATIEC", matieccuoi);
                command.Parameters.AddWithValue("@MACA", _MaCa.Trim());
                command.Parameters.AddWithValue("@MASANH", _MaSanh.Trim());
                command.ExecuteNonQuery();
                command.Dispose();
            }
            catch (Exception emon)
            {
                MessageBox.Show(emon.Message);
                _LoiInsert = true;
                return;
            }
        }

        private void LayMaSanhMaCa()
        {
            if (radioButton1.Checked == true)
            {
                _MaCa = "CA001";
            }
            else
            {
                _MaCa = "CA002";
            }
            foreach (ListViewItem item in listSanh.Items)
            {
                if (item.Checked == true)//lay sanh dc chon
                {
                   // _MaSanh = item.SubItems[1].ToString();
                    _MaSanh = this.listSanh.Items[item.Index].SubItems[1].Text.Trim();
                }
            }

        }

        private void InsertHoaDon(string MaHoaDon,string MaTiec)
        {
            //insert tiec cuoi
            string ngaythanhtoan = dateTimePicker1_ngaysinh.Value.ToShortDateString();
            string TongTien = TB_ThanhTien.Text;
            TongTien = TongTien.Replace(",", "");
            try
            {
                string cmd = "INSERT INTO HOADON VALUES(@MAHD,@MATIECCUOI,@NGAYTHANHTOAN,@NGAYCHENHLECH,@TONGTIENBAN,@TONGTIENDV,@TONGTIENHOADON,@TIENPHAT,@TONGTIEN)";
                SqlCommand command = new SqlCommand(cmd, _CNN);
                command.CommandType = CommandType.Text;
                command.Parameters.AddWithValue("@MAHD", MaHoaDon);
                command.Parameters.AddWithValue("@MATIECCUOI",MaTiec);
                command.Parameters.AddWithValue("@NGAYTHANHTOAN", ngaythanhtoan);
                command.Parameters.AddWithValue("@NGAYCHENHLECH", 0);
                command.Parameters.AddWithValue("@TONGTIENBAN",TB_Tongtienban.Text.Trim());
                command.Parameters.AddWithValue("@TONGTIENDV", TB_TongtienDV.Text.Trim());
                command.Parameters.AddWithValue("@TONGTIENHOADON",TB_ThanhTien.Text.Trim()  );
                command.Parameters.AddWithValue("@TIENPHAT", 0);
                command.Parameters.AddWithValue("@TONGTIEN", TongTien);
                command.ExecuteNonQuery();
                command.Dispose();
            }
            catch (Exception emon)
            {
                MessageBox.Show(emon.Message);
                _LoiInsert = true;
                return;
            }
        }

        private void InsertCTHD(string maDATBAN, string mactdichvu)
        {
            //insert tiec cuoi
            string ma = CreateMaCTHD(_MAHD);
            string ngaythanhtoan = DateTime.Now.Month.ToString() + "/" + DateTime.Now.Day.ToString() + "/" + DateTime.Now.Year.ToString();
            try
            {
                string cmd = "INSERT INTO CHITIETHOADON VALUES(@MACTHD,@MACHITIETDV,@MAHOADON,@MADATBAN,@TONGTIENBAN,@TONGTIENDICHVU)";
                SqlCommand command = new SqlCommand(cmd, _CNN);
                command.CommandType = CommandType.Text;
                command.Parameters.AddWithValue("@MACTHD", ma);
                command.Parameters.AddWithValue("@MACHITIETDV", mactdichvu);
                command.Parameters.AddWithValue("@MAHOADON", _MAHD);
                command.Parameters.AddWithValue("@MADATBAN", maDATBAN);
                command.Parameters.AddWithValue("@TONGTIENBAN",TB_Tongtienban.Text.Trim());
                command.Parameters.AddWithValue("@TONGTIENDICHVU",TB_TongtienDV.Text.Trim());
                command.ExecuteNonQuery();
                command.Dispose();
            }
            catch (Exception emon)
            {
                MessageBox.Show(emon.Message);
                _LoiInsert = true;
                return;
            }
        }
    }
}
